const explain = require("explain")
const uniID = require('uni-id')

module.exports = class user extends explain.service {
	async updateCert(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('uni-id-users').where({
			_id: payload.uid
		}).update({
			paramedic_profile: {
				certificates: dbCmd.push({
					title: params.title,
					image: params.image
				})
			}
		})
	}

	async updateLocation(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		return await db.collection('uni-id-users').doc(payload.uid).update({
			location: {
				coordinates: [
					params.lng,
					params.lat
				],
				type: "Point"
			}
		})
	}

	async getUserLocations(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()

		return await db.collection('uni-id-users').field({
				location: true
			})
			.where({
				role: 'user',
				location: db.command.neq(null)
			}).get()
	}

	async getMyInfo(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const service = await db.collection('services').doc(payload.userInfo.paramedic_profile.service_id)
			.get()
		const hospital = await db.collection('hospitals').doc(payload.userInfo.paramedic_profile.hospital_id)
			.get()
		const plus = await db.collection('attach_services').where({
			_id: db.command.in(payload.userInfo.paramedic_profile.plus)
		}).get()
		return {
			service: service.data[0].title,
			hospital: hospital.data[0].name,
			plus: plus.data
		}
	}
}
